import 'package:fish_redux/fish_redux.dart';

import 'action.dart';
import 'state.dart';

Reducer<AnswerEditState> buildReducer() {
  return asReducer(
    <Object, Reducer<AnswerEditState>>{
      AnswerEditAction.initCamera: _initCamera,
      AnswerEditAction.doingOcr: _doingOcr,
      AnswerEditAction.doneOcr: _doneOcr,
      AnswerEditAction.selectGrade: _selectGrade,
      AnswerEditAction.selectType: _selectType,
      AnswerEditAction.token: _token,
      AnswerEditAction.aiCommitted: _aiCommitted,
      AnswerEditAction.focus: _focus,
    },
  );
}

AnswerEditState _initCamera(AnswerEditState state, Action action) {
  final AnswerEditState newState = state.clone()
    ..camera = action.payload['camera']
    ..controller = action.payload['controller'];
  return newState;
}

AnswerEditState _selectGrade(AnswerEditState state, Action action) {
  return state.clone()..answer.grade = action.payload;
}

AnswerEditState _selectType(AnswerEditState state, Action action) {
  return state.clone()..answer.articleType = action.payload;
}

AnswerEditState _doingOcr(AnswerEditState state, Action action) {
  int index = action.payload;
  final AnswerEditState newState = state.clone()..currentOcrIndex = index;
  return newState;
}

AnswerEditState _doneOcr(AnswerEditState state, Action action) {
  final AnswerEditState newState = state.clone();
  Map<String, String> ocr = action.payload;
  var title = ocr['title'];
  if (newState.titleEditController.text.isEmpty) {
    newState.titleEditController.text += title.replaceAll('null', '');
    title = '';
  }
  newState.contentEditController.text += title + ocr['content'];
  if (newState.currentOcrIndex == newState.photos.length - 1) {
    newState.currentOcrIndex += 1;
  }
  return newState;
}

AnswerEditState _token(AnswerEditState state, Action action) {
  final AnswerEditState newState = state.clone()..aliToken = action.payload;
  return newState;
}

AnswerEditState _aiCommitted(AnswerEditState state, Action action) {
  return state.clone()..aiCommitted = true;
}

AnswerEditState _focus(AnswerEditState state, Action action) {
  return state.clone()..isTitle = action.payload;
}
